package gui;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JColorChooser;

import zerdlib.events.GenericListenable;


public class ColorJButton extends JButton implements GenericListenable<ColorChangeListener> {
	private GenericListenable<ColorChangeListener> listenable = new GenericListenable<>();
	private static final long serialVersionUID = 984019782595319638L;
	private Color color;
	
	
	public ColorJButton(Color color) {
		super();
		setColor(color);
		
		this.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ev) {
				ColorJButton source = (ColorJButton)ev.getSource(); 
				source.setColor(JColorChooser.showDialog(source, "Choisissez une couleur", source.color));
			}
		});
	}
	
	private void setColor(Color color) {
		this.color = color;
		this.setBackground(color);
		fireColorChange();
	}
	
	public Color getColor() {
		return color;
	}

	public void addWeakListener(ColorChangeListener l) {
		listenable.addWeakListener(l);
	}

	public void addListener(ColorChangeListener l) {
		listenable.addListener(l);
	}

	public void removeListener(ColorChangeListener l) {
		listenable.removeListener(l);
	}
	
	private void fireColorChange() {
			for(ColorChangeListener l : listenable.getListeners(ColorChangeListener.class)) {
				l.onColorChanged(this, color);
			}
		}
	}

